<template>
    <div class="plot-car">
        <el-row>
            <el-col :span="24">
                <el-form ref="queryFormRef" :model="queryForm" inline size="mini">
                    <el-form-item>
                        <el-input v-model="queryForm.carNumber" placeholder="车牌号" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button plain @click="handleReset">重置</el-button>
                        <el-button type="primary" plain @click="handleAdd">添加</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>


        <!-- 车辆列表 -->
        <el-table :data="carList" border stripe style="width: 100%" ref="table"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="carNumber" label="车牌号" align="center" />
            <el-table-column prop="name" label="人员姓名" align="center" />
            <el-table-column prop="phoneNumber" label="手机号码" align="center" />
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" width="150" align="center">
                <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleEdit(row.carId)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(row.carId, row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page.sync="paginate.pageNum" :page-sizes="[5, 10, 15]" :page-size.sync="paginate.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" />

        <!-- 新增,编辑弹窗 -->
        <el-dialog :visible.sync="dialog.visible" width="30%" @close="handleClose">
            <template #title>{{ dialog.isEdit ? "编辑车辆" : "添加车辆" }}</template>
            <el-form ref="dialogFormRef" :model="dialog.form" :rules="dialog.rules" label-width="80px">
                <el-form-item label="车牌号" prop="carNumber">
                    <el-input v-model="dialog.form.carNumber" />
                </el-form-item>
                <el-form-item label="车主" prop="personId">
                    <el-select v-model="dialog.form.personId" placeholder="请选择车主" filterable
                        @click.native="openPersonSelectDialog">
                        <el-option v-for="item in personList" :key="item.personId" :label="item.name"
                            :value="item.personId" />
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
        </el-dialog>

        <!-- 选择人员弹窗 -->
        <el-dialog :visible.sync="personSelectDialog.visible" width="45%" @close="personSelectDialog.visible = false">

            <el-col :span="24">
                <el-form ref="personQueryFormRef" :model="personQueryForm" inline size="mini">
                    <template #title>{{ 选择人员 }}</template>
                    <el-form-item>
                        <el-input v-model="personQueryForm.name" placeholder="人员名字" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handlePersonQuery">查询</el-button>
                        <el-button plain @click="handlePersonReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>

            <!-- 人员信息表 -->
            <el-table :data="personSelectList" border stripe style="width: 100%;margin-top: 60px;">
                <el-table-column type="index" label="序号" width="50" align="center" />
                <el-table-column prop="name" label="人员名字" align="center" />
                <el-table-column label="操作" width="100" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="selectPerson(row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 人员信息表分页 -->
            <el-pagination @size-change="handlePersonSizeChange" @current-change="handlePersonCurrentChange"
                :current-page.sync="personPaginate.pageNum" :page-sizes="[5, 10, 15]"
                :page-size.sync="personPaginate.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="personPaginate.total" />


        </el-dialog>
    </div>
</template>

<script>
import { addPlotCarInfo, queryCurPlotCarInfo, queryPlotCarList, queryPlotCarDtl, updatePlotCarInfo, deletePlotCarInfo, } from "@/api/car.js"
import { checkQueryInput, restForm } from '@/utils/tool'

export default {
    name: "car",
    data() {
        return {
            // 锁
            isLock:false,

            // 小区车辆列表
            carList: [],

            // 小区人员列表
            personList: [],

            // 表单
            queryForm: {
                carNumber: "",
                plotId: this.getCurrentPlotId()
            },

            // 分页信息
            paginate: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
            },

            //添加，编辑弹窗
            dialog: {
                visible: false,
                isEdit: false,
                form: {
                    carId: "",
                    carNumber: "",
                    personId: "",
                },
                rules: {
                    carNumber: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
                    personId: [{ required: true, message: "请选择所属人员", trigger: "change" }],
                },
            },

            // 选择人员弹窗
            personSelectDialog: {
                visible: false
            },
            // 选择人员表单
            personQueryForm: {
                name: "",
                plotId: this.getCurrentPlotId()
            },
            // 选择人员列表
            personSelectList: [],
            // 选择人员分页
            personPaginate: {
                pageNum: 1,
                pageSize: 5,
                total: 0
            },

            // 批量删除
            ids: [],//存储选中的所有小区ID
            single: true,//标记是否不是单选
            multiple: false//标记是否没有选中数据

        }
    },

    created() {
        this.getCarList()
        this.getPersonList()

        // 监听小区id变化
        this.$watch(
            function () {
                return this.$store.state.plot.currentPlot?.plotId
            }.bind(this),

            function (newPlotId) {
                const plotId = newPlotId || 1;
                this.queryForm.plotId = plotId
                this.personQueryForm.plotId = plotId
                this.getCarList()
                this.getPersonList()
            }
        )
    },


    methods: {
        // 拿到当前小区id
        getCurrentPlotId() {
            return this.$store.state.plot.currentPlot?.plotId || 1
        },

        // 拿到车辆列表
        getCarList() {
            const { total, ...rest } = this.paginate
            const { carNumber, ...plotId } = this.queryForm
            const params = {
                ...rest,
                ...plotId
            }

            // 查询车辆的列表
            return queryPlotCarList(params).then((res) => {
                this.carList = res.rows || []
                this.paginate.total = res.total || 0
                if (this.carList.length === 0 && this.queryForm.carNumber) {
                    this.$message.info("未查询到符合条件的车辆")
                }
                return res
            })
        },

        // 拿到人员列表
        getPersonList() {
            return queryCurPlotCarInfo({
                pageNum: 1,
                pageSize: 1000,
                plotId: this.getCurrentPlotId(),
            }).then((res) => {
                this.personList = res.rows || []
                return res
            })
        },

        // 查询
        handleQuery() {
            const hasInput = checkQueryInput({ carNumber: this.queryForm.carNumber })
            if (!hasInput) return this.$message.warning("当前没有输入值，请至少输入一项数据!!")
            this.paginate.pageNum = 1
            this.getCarList().then(() => {
                this.$message.success("查询成功")
            });
        },


        // 重置
        handleReset() {
            // 手动清空表单数据
            this.queryForm.carNumber = ""
            if (this.$refs.queryFormRef) {
                restForm(this.$refs.queryFormRef)
            }
            this.paginate.pageNum = 1;
            this.getCarList().then(() => {
                this.$message.success("重置成功")
            });
        },

        // 分页
        handleSizeChange(size) {
            this.paginate.pageSize = size
            this.getCarList()
        },
        handleCurrentChange(page) {
            this.paginate.pageNum = page
            this.getCarList()
        },


        // 添加
        handleAdd() {
            this.dialog.visible = true
            this.dialog.isEdit = false
            this.dialog.form = {
                carId: "",
                carNumber: "",
                personId: "",
            }
        },


        // 编辑
        handleEdit(carId) {
            queryPlotCarDtl(carId).then((res) => {
                this.dialog.visible = true
                this.dialog.isEdit = true
                this.dialog.form = {
                    carId: res.data.carId,
                    carNumber: res.data.carNumber,
                    personId: res.data.personId,
                }
            })
        },


        // 提交
        handleSubmit() {
            if(this.isLock) return
            this.$refs.dialogFormRef.validate((valid) => {
                if (!valid) return
                this.isLock=true
                const api = this.dialog.isEdit ? updatePlotCarInfo : addPlotCarInfo
                api(this.dialog.form).then(() => {
                    this.$message.success("操作成功")
                    this.dialog.visible = false
                    this.getCarList()
                    this.isLock=false
                })
            })
        },

        // 关闭
        handleClose() {
            this.dialog.visible = false;
            this.dialog.form = {
                carId: "",
                carNumber: "",
                personId: "",
            };
            if (this.$refs.dialogFormRef) {
                restForm(this.$refs.dialogFormRef)
            }
        },


        // 批量删除的选中事件
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.carId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        // 删除
        handleDelete(carId, row) {
            const carIds = this.ids.length > 0 ? this.ids : [carId]

            const carIdsStr = carIds.join(',')

            const count = carIds.length

            this.$confirm(`确定删除选中的【${count}】条车辆信息吗？`, "提示", {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: "warning",
            }).then(() => {
                return deletePlotCarInfo(carIdsStr).then(() => {
                    this.getCarList()
                    this.$message.success("删除成功")
                    this.$refs.table.clearSelection()
                })
            }).catch((err) => {
                console.log(err);
            })
        },

        // 打开人员选择弹窗
        openPersonSelectDialog() {
            this.personSelectDialog.visible = true;
            this.getPersonSelectList()
        },

        // 拿到人员选择列表
        getPersonSelectList() {
            const { total, ...rest } = this.personPaginate;
            const params = {
                ...rest,
                ...this.personQueryForm,
                name: this.personQueryForm.name.trim()
            };
            return queryCurPlotCarInfo(params).then((res) => {
                this.personSelectList = res.rows || []
                this.personPaginate.total = res.total || 0
                if (this.personSelectList.length === 0 && this.personQueryForm.name) {
                    this.$message.info("未查询到符合条件的人员")
                }
                return res
            });
        },

        // 人员选择查询
        handlePersonQuery() {
            const hasInput = checkQueryInput(this.personQueryForm);
            if (!hasInput) return this.$message.warning("当前没有输入值，请至少输入一项数据!!")
            this.personPaginate.pageNum = 1;
            this.getPersonSelectList().then(() => {
                this.$message.success("查询成功")
            })
        },

        // 人员选择重置
        handlePersonReset() {
            this.personQueryForm.name = "";
            if (this.$refs.personQueryFormRef) {
                restForm(this.$refs.personQueryFormRef)
            }
            this.personPaginate.pageNum = 1
            this.getPersonSelectList().then(() => {
                this.$message.success("重置成功")
            })
        },

        // 人员选择分页
        handlePersonSizeChange(size) {
            this.personPaginate.pageSize = size
            this.getPersonSelectList()
        },
        handlePersonCurrentChange(page) {
            this.personPaginate.pageNum = page
            this.getPersonSelectList()
        },
        selectPerson(row) {
            this.dialog.form.personId = row.personId
            this.personSelectDialog.visible = false
        }
    },

}
</script>

<style lang="scss" scoped>
.plot-car {
    padding: 20px;
}
</style>